package com.ash.socketb.dual.end;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

/**
 * 客户端连接方式
 * 1. 客户端可以使用telnet工具进行连接
 * 2. 自己写socket客户端连接
 */
public class ServerDualDemo {

    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(8081);

        do {
            Socket oneConnect = serverSocket.accept();
            System.out.println("有客户来了:" + oneConnect);

            handleConnect(oneConnect);

        } while (true);

    }

    /**
     * 可以使用异步处理，这里主要是演示功能，不做异步处理方式。简化案例复杂度
     *
     * @param accept
     * @throws IOException
     */
    private static void handleConnect(Socket accept) {
        try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(accept.getInputStream()));
             OutputStream outputStream = accept.getOutputStream()
        ) {


            abort: while (true) {
                StringBuilder requestPayload = new StringBuilder();
                String line = null;
                while ((line = bufferedReader.readLine()) != null) {
                    if ("end".equals(line)) {
                        System.out.println("读取请求内容结束");
                        break;
                    }

                    if ("close".equals(line)) {
                        System.out.println("连接断开");
                        break abort;
                    }

                    System.out.println(line);
                    // 这里要加\n 不然客户端读取readline时不知道什么时候结束
                    requestPayload.append(line + "\n");
                }

                // 处理响应
                outputStream.write(requestPayload.toString().getBytes(StandardCharsets.UTF_8));
                // 同样你也告诉客户端我写完了
                outputStream.write("end\n".getBytes(StandardCharsets.UTF_8));
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
